<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App\Func;

use Core\Func\CoreFunc as CoreFunc;
use Model\Admin\CategoryModel as CategoryModel;

/**
 * 表单函数库
 */
class Form extends CoreFunc {

    /**
     * 时间戳转换正常时间
     * @param int $date 时间戳
     * @param str $type 显示类型
     * @return date 返回时间
     */
    function toDate($date, $type = 'Y-m-d H:i:s') {
        return date($type, $date);
    }

    /**
     * 获取字段类型
     * @param str $type 字段名称
     * @return string 返回对应的字段
     */
    function fieldType($type) {
        switch ($type) {
            case 'category':
                return '分类';
                break;
            case 'text':
                return '单行文本框';
                break;

            case 'select':
                return '下拉菜单';
                break;

            case 'checkbox':
                return '复选框';
                break;

            case 'radio':
                return '单选框';
                break;

            case 'textarea':
                return '多行文本框';
                break;

            case 'thumb':
                return '略缩图';
                break;

            case 'editor':
                return '编辑器';
                break;

            case 'img':
                return '图组';
                break;

            case 'file':
                return '上传文件';
                break;

            case 'date':
                return '时间控件';
                break;

            default:
                return '未知字段类型';
                break;
        }
    }

    /**
     * 列出对应的表单
     * @param array $field
     * @return string
     */
    function formList(array $field) {
        $str = '';
        switch ($field['type']) {
            case 'category':
                CategoryModel::$where = 'pm.model_name = "' . MODULE . '"';
                $tree = CategoryModel::getSelectCate($field['value'] ? $field['value'] : '');
                return '<select name="' . $field['field_name'] . '">' . $tree . '</selete>';
                break;
            case 'text':
                return '<input name="' . $field['field_name'] . '" type="text" class="input length_5" aria-label="' . $field['name'] . '" accesskey="s" placeholder="' . $field['name'] . '" speech="" value="' . $field['value'] . '">';
                break;

            case 'select':
                foreach (json_decode($field['option']) as $key => $value) {
                    if (isset($field['value'])) {
                        $selected = $field['value'] == $key ? 'selected="selected" ' : '';
                        $str .= '<option value="' . $key . '" ' . $selected . '>' . $value . '</option>';
                    } else {
                        $selected = $field['default'] == $key ? 'selected="selected" ' : '';
                        $str .= '<option value="' . $key . '" ' . $selected . '>' . $value . '</option>';
                    }
                }
                return '<select name="' . $field['field_name'] . '">' . $str . '</select>';
                break;

            case 'checkbox':
                if (isset($field['value'])) {
                    $checked_value = explode(',', $field['value']);
                } elseif (isset($field['default'])) {
                    $checked_value = explode(',', $field['default']);
                } else {
                    $checked_value = array();
                }
                foreach (json_decode($field['option']) as $key => $value) {
                    if (in_array($key, $checked_value)) {
                        $str .= '<label><input type="checkbox" name="' . $field['field_name'] . '[]" value="' . $key . '" checked="checked" /><span>' . $value . '</span></label>';
                    } else {
                        $str .= '<label><input type="checkbox" name="' . $field['field_name'] . '[]" value="' . $key . '" /><span>' . $value . '</span></label>';
                    }
                }
                return $str;
                break;

            case 'radio':
                foreach (json_decode($field['option']) as $key => $value) {
                    if (isset($field['value'])) {
                        $checked = $field['value'] == $key ? 'checked="checked" ' : '';
                        $str .= '<label><input type="radio" name="' . $field['field_name'] . '" value="' . $key . '" ' . $checked . '/><span>' . $value . '</span></label>';
                    } else {
                        $checked = $field['default'] == $key ? 'checked="checked" ' : '';
                        $str .= '<label><input type="radio" name="' . $field['field_name'] . '" value="' . $key . '" ' . $checked . '/><span>' . $value . '</span></label>';
                    }
                }
                return $str;
                break;

            case 'textarea':
                return '<textarea name="' . $field['field_name'] . '" cols="55">' . $field['value'] . '</textarea>';
                break;

            case 'thumb':
                //是否显示已上传的缩略图
                $display = "display:none";
                $model = MODULE;
                if (!empty($field['value'])) {
                    $_COOKIE["input_{$field['field_name']}"] = $field['value'];
                    $outInput = '<img src="' . $_COOKIE["input_{$field['field_name']}"] . '" class="thumbImg" width="128" />';
                    $display = "display:block";
                } elseif (!empty($_COOKIE["input_{$field['field_name']}"])) {
                    $outInput = '<img src="' . $_COOKIE["input_{$field['field_name']}"] . '" class="thumbImg" width="128" />';
                    $display = "display:block";
                }

                $outhtml = <<<EOT
                    <input id="{$field['field_name']}_upload" name="file_upload" type="file" multiple="true"/>
                    <input name="{$field['field_name']}" type="hidden" class="input length_5" value="{$_COOKIE["input_{$field['field_name']}"]}" />
                    <div class="{$field['field_name']}_preview" style="border-top:1px solid #000;margin-top:5px;padding-top:5px;width:130px;height:auto;{$display}">
                        <span class="{$field['field_name']}_preview_img" >{$outInput}</span>
                        <a href="javascript:deletePreview('{$field['field_name']}_preview', '{$field['field_name']}_preview_img');" class="btn btn_submit J_ajax_submit_btn" style="margin-top:10px;">删除</a>
                    </div>
                    <script type="text/javascript">
                        function deletePreview(parent, child) {
                            $("." + parent).hide();
                            $("." + child).html("");
                            //清空表单值
                            $("input[name={$field['field_name']}]").val("");
                            //清空cookie
                            setCookie('input_{$field['field_name']}', '');
                        }
                        uetjs.{$field['field_name']}_upload = function(){
                        $('#{$field['field_name']}_upload').uploadify({
                            'formData': {
                                'type': 'img'
                            },
                            'fileTypeDesc': 'Image Files',
                            'fileTypeExts': '*.gif; *.jpg; *.png',
                            'queueSizeLimit' : 1,
                            'width': 60,
                            'height': 60,
                            'buttonText': '',
                            'swf': '/Component/uploadify/uploadify.swf',
                            'uploader': '/index.php/Admin-Upload-index',
                            'onUploadSuccess': function(file, data, response) {
                                objData = JSON.parse(data);
                                switch (objData['status']) {
                                    case 0:
                                        art.dialog({
                                            title: '提示',
                                            content: objData.info,
                                            time: 2000
                                        });
                                        break;
                                    case 1:
                                        art.dialog({
                                            title: '提示',
                                            content: objData['info']['0'],
                                            time: 2000
                                        });
                                        setCookie('input_{$field['field_name']}', objData['info']['1']);
                                        $(".{$field['field_name']}_preview").show();
                                        $(".{$field['field_name']}_preview_img").html('<img src="' + objData['info']['1'] + '" class="thumbImg" width="400" height="300" />');
                                        $("input[name={$field['field_name']}]").val(objData['info']['1']);
                                        break;
                                    default:
                                        alert("未知状态码");
                                }
                            }
                        });
                        }
                    </script>
EOT;
                return $outhtml;
                break;

            case 'editor':
                return '<textarea id="editor_id" name="' . $field['field_name'] . '" style="width:700px;height:300px;">' . $field['value'] . '</textarea>';
                break;

            case 'img':
                return $this->commonUploadCode($field['field_name'], 'img', $field['value']);
                break;

            case 'file':
                return $this->commonUploadCode($field['field_name'], 'file', $field['value']);
                break;

            case 'date':
                return '<input name="' . $field['field_name'] . '" type="text" class="input length_5 datepicker" aria-label="' . $field['name'] . '" accesskey="s" placeholder="' . $field['name'] . '" speech="" value="' . $this->toDate(empty($field['value']) ? time() : $field['value'], 'Y-m-d') . '" readonly="readonly">';
                break;

            default:
                return '未知字段类型';
                break;
        }
    }

    /**
     * 公共前台的上传代码
     * @param type $fieldName 字段名称
     * @param type $type 上传类型
     */
    private function commonUploadCode($fieldName, $type, $fileValue = '') {
        $model = MODULE;
        switch ($type) {
            case 'img':
                $formType = "'type': 'img'";
                $fileTypeDesc = "'fileTypeDesc': 'Image Files',";
                $fileTypeExts = "'fileTypeExts': '*.gif; *.jpg; *.png',";
                break;
            case 'file':
                $formType = "'type': 'file'";
                $fileTypeDesc = "'fileTypeDesc': 'All Files',";
                $fileTypeExts = "'fileTypeExts': '*.*',";
                break;
        }

        if (!empty($fileValue)) {
            /**
             * 由于PHP setcookie会报警告，顾采用输出JS方式来设置cookie
             * 此处设置cookie 用于 删除功能的实现
             */
            echo "<script>$(function(){setCookie('input_{$fieldName}', '$fileValue');})</script>";
            $input_array = explode(',', $fileValue);
            $outInput = '';
            foreach ($input_array as $value) {
                $outInput .= '<div><input name="' . $fieldName . '[]" type="text" class="input length_5" value="' . $value . '" style="margin:5px 10px 6px 0;"><a href="javascript:void(0);" class="btn btn_submit J_ajax_submit_btn clearUploadImg" data="input_' . $fieldName . '">删除</a></div>';
            }
        } elseif (!empty($_COOKIE["input_{$fieldName}"])) {
            $input_array = explode(',', $_COOKIE["input_{$fieldName}"]);
            $outInput = '';
            foreach ($input_array as $value) {
                $outInput .= '<div><input name="' . $fieldName . '[]" type="text" class="input length_5" value="' . $value . '" style="margin:5px 10px 6px 0;"><a href="javascript:void(0);" class="btn btn_submit J_ajax_submit_btn clearUploadImg" data="input_' . $fieldName . '">删除</a></div>';
            }
        }

        $outhtml = <<<EOT
        <input id="{$fieldName}_upload" name="{$fieldName}_upload" type="file" multiple="true"/><div id="{$fieldName}_inputs">{$outInput}</div>
        <script type="text/javascript">
        uetjs.{$fieldName}_upload = function(){
            temp_array = "{$_COOKIE["input_{$fieldName}"]}";
            var input_{$fieldName} = [];
            //为空则不处理
            if(temp_array != ''){
                input_{$fieldName} = temp_array.split(',');
            }
            $('#{$fieldName}_upload').uploadify({
                'formData': {
                    $formType
                },
                'width': 60,
                'height': 60,
                'buttonText': '',
                $fileTypeDesc
                $fileTypeExts
                'swf': '/Component/uploadify/uploadify.swf',
                'uploader': '/index.php/Admin-Upload-index',
                'onUploadSuccess': function(file, data, response) {
                    objData = JSON.parse(data);
                    switch (objData['status']) {
                        case 0:
                            art.dialog({
                                title: '提示',
                                content: objData.info,
                                time: 2000
                            });
                            break;
                        case 1:
                            input_{$fieldName}.push(objData['info']['1']);
                            str_input_{$fieldName} = input_{$fieldName}.join(',');
                            setCookie('input_{$fieldName}', str_input_{$fieldName});
                            $("#{$fieldName}_inputs").append('<div><input name="{$fieldName}[]" type="text" class="input length_5" value="' + objData['info']['1'] + '" style="margin:5px 10px 6px 0;"><a href="javascript:void(0);" class="btn btn_submit J_ajax_submit_btn clearUploadImg" data="input_{$fieldName}">删除</a></div>');
                            break;
                        default:
                            alert("未知状态码");
                    }
                }
            });
        }
        </script>
EOT;
        return $outhtml;
    }

}
